package com.itlong.cloud.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.PO.ProjectPO;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.push.JPushClientService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 *      项目蓝牙电梯更新队列消费者
 * </desc>
 *
 * @createDate 2018-08-06.
 */
@Component
public class ProjectBluetoothElevatorJPushConsumer {
    private static final Logger LOG = LoggerFactory.getLogger(ProjectBluetoothElevatorJPushConsumer.class);

    @Autowired
    JPushClientService jPushClientService;

    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_PROJECT_BLUETOOTH_ELEVATOR_QUEUE)
    public void process(Message message, Channel channel) throws InterruptedException, IOException {
        byte[] body = message.getBody();
        try {
            TimeTaskDeadMessageQueuePO timeTaskDeadMessageQueuePO = JSON.parseObject(new String(body), TimeTaskDeadMessageQueuePO.class);
            JSONObject js = JSON.parseObject(timeTaskDeadMessageQueuePO.getMessageContent());
            ProjectPO projectPO = js.getObject("data", ProjectPO.class);
            if (projectPO != null) {
                //推送刷新指令
                Map<String, String> cmd = new HashMap<>();
                cmd.put("isBluetoothElevator",projectPO.getIsBluetoothElevator().toString());
                JSONObject json = new JSONObject();
                json.put("isBluetoothElevator",projectPO.getIsBluetoothElevator());
                String msg = json.toString();

                jPushClientService.pushWithProjectTask(projectPO.getProjectId(), cmd, msg,
                        "100000".equals(projectPO.getCountryId()) ? 1 : 2);
            }
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            LOG.error("【RabbitMQ_项目蓝牙电梯状态变更极光推送业务消费端】:解析异常",e);
        } finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
